<?php

class bdMysql {
	var $link;
	var $db;
	var $host, $user, $pass;
	var $sql;
	var $queryCount;
	var $queryList;


	function bdMysql($db, $host="localhost", $user="", $pass="") {
		$this->queryCount = 0;
		$this->queryList = array();
		$this->db = $db; $this->host = $host; $this->user = $user; $this->pass = $pass;
		if($this->link = mysql_connect($host,$user,$pass))
			return mysql_select_db($db, $this->link);
			else return 0;
	}

	function query($sql) {
		if(!$this->link) return 0;
		$this->queryCount += 1;
		$this->queryList[] = $sql;
		return mysql_query($this->sql = $sql, $this->link);
	}

	function queryOrDie($sql)
	{
		$D = $this->query($sql) or die(mysql_error());
		return $D;
	}


	function affected_rows() {
		return mysql_affected_rows($this->link);
	}


	function num_rows($q) {
		return mysql_num_rows($q);
	}

	function fetch_array($q, $result_type=MYSQL_ASSOC) {
		return mysql_fetch_array($q, $result_type);
	}

	function fetchOrDie($q, $result_type=MYSQL_ASSOC)
	{
		$result = $this->fetch_array($q, $result_type) or die("SQL error: Empty dataset");
		return $result;
	}

	function insert_id() {
		return mysql_insert_id($this->link);
	}


	function insert($tabla, $datos)
	{
		$sql = "INSERT INTO $tabla(".$this->keys($datos).") VALUES(".$this->vals($datos).") ";
                $q = $this->queryOrDie($sql);
		if(!$q || 1 != $this->affected_rows($q)) return false;
		return $this->insert_id();
	}

        function keys($arr)
	{
		$F = array();
		foreach($arr as $k => $v) $F[] = mysql_real_escape_string($k);
		return implode(', ', $F);
	}
	function vals($arr)
	{
		$F = array();
		foreach($arr as $k => $v) if(is_null($v)) $F[] = 'NULL'; else $F[] = "'".mysql_real_escape_string($v)."'";
		return implode(", ", $F);
	}
        function update($tabla, $D,$id, $MOD ){
                $i=0;
                $conjunto="";
               foreach($D as $campo => $valor){
                        $conjunto.=$campo ."='".$valor."',";
                    $i++;
               }
               $conjunto=rtrim($conjunto, ",");
                $this->queryOrDie("UPDATE {$tabla} SET {$conjunto} WHERE {$MOD}_id={$id}");
        }


}



?>
